package com.cinc.mdm.modules.material.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cinc.mdm.constant.MdmConstant;
import com.cinc.mdm.modules.codeRule.service.IMdmCodeRuleService;
import com.cinc.mdm.modules.material.entity.MdmMaterial;
import com.cinc.mdm.modules.material.entity.MdmMaterialFactoryDetail;
import com.cinc.mdm.modules.material.entity.MdmMaterialFinanceDetail;
import com.cinc.mdm.modules.material.entity.MdmMaterialUnitDetail;
import com.cinc.mdm.modules.material.service.IMdmMaterialFactoryDetailService;
import com.cinc.mdm.modules.material.service.IMdmMaterialFinanceDetailService;
import com.cinc.mdm.modules.material.service.IMdmMaterialService;
import com.cinc.mdm.modules.material.service.IMdmMaterialUnitDetailService;
import com.cinc.mdm.modules.material.vo.MdmMaterialPage;
import com.cinc.mdm.modules.sysParam.entity.MdmSysParam;
import com.cinc.mdm.modules.sysParam.service.IMdmSysParamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: mdm_material
 * @Author: jeecg-boot
 * @Date:   2021-10-13
 * @Version: V1.0
 */
@Api(tags="mdm_material")
@RestController
@RequestMapping("/mdm/material")
@Slf4j
public class MdmMaterialController extends JeecgController<MdmMaterial, IMdmMaterialService> {
	@Autowired
	private IMdmMaterialService mdmMaterialService;
	@Autowired
	private IMdmMaterialFactoryDetailService mdmMaterialFactoryDetailService;
	@Autowired
	private IMdmMaterialFinanceDetailService mdmMaterialFinanceDetailService;
	@Autowired
	private IMdmMaterialUnitDetailService mdmMaterialUnitDetailService;
	@Autowired
	private IMdmSysParamService mdmSysParamService;
	@Autowired
	private IMdmCodeRuleService mdmCodeRuleService;


	/**
	 * 分页列表查询
	 *
	 * @param mdmMaterial
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@PermissionData(pageComponent = "mdm/material/MdmMaterialMainList")
	@AutoLog(value = "mdm_material-分页列表查询")
	@ApiOperation(value="mdm_material-分页列表查询", notes="mdm_material-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MdmMaterial mdmMaterial,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MdmMaterial> queryWrapper = QueryGenerator.initQueryWrapper(mdmMaterial, req.getParameterMap());
		Page<MdmMaterial> page = new Page<MdmMaterial>(pageNo, pageSize);
		IPage<MdmMaterial> pageList = mdmMaterialService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 物料自动编码校验
	 */
	@AutoLog(value = "物料自动编码校验")
	@ApiOperation(value="物料自动编码校验", notes="物料自动编码校验")
	@GetMapping(value = "/checkMaterialCodeGenerate")
	public Result<?> checkMaterialCodeGenerate() {
		LambdaQueryWrapper<MdmSysParam> sysParamQueryWrapper = new LambdaQueryWrapper<>();
		sysParamQueryWrapper.eq(MdmSysParam::getParamCode, MdmConstant.SYS_PARAM001)
				.eq(MdmSysParam::getEnableFlag, "1")
				.eq(MdmSysParam::getValue, "1");
		MdmSysParam mdmSysParam = mdmSysParamService.getOne(sysParamQueryWrapper);
		if(mdmSysParam == null){
			return Result.OK(false);
		}else{
			return Result.OK(true);
		}
	}

	/**
	 * 物料编码生成
	 */
	@AutoLog(value = "物料编码生成")
	@ApiOperation(value="物料编码生成", notes="物料编码生成")
	@GetMapping(value = "/genMaterialCode")
	public Result<?> genMaterialCode() {
		LambdaQueryWrapper<MdmSysParam> sysParamQueryWrapper = new LambdaQueryWrapper<>();
		sysParamQueryWrapper.eq(MdmSysParam::getParamCode, MdmConstant.SYS_PARAM001)
				.eq(MdmSysParam::getEnableFlag, "1")
				.eq(MdmSysParam::getValue, "1");
		MdmSysParam mdmSysParam = mdmSysParamService.getOne(sysParamQueryWrapper);
		if(mdmSysParam == null){
			return Result.OK();
		}else{
			String code = mdmCodeRuleService.generateCodeByCodeType(MdmConstant.CODE_TYPE01);
			if(StringUtils.isBlank(code)){
				return Result.error("编码规则无效");
			}else{
				return Result.OK(code);
			}
		}
	}

	/**
	 *   添加
	 *
	 * @param mdmMaterialPage
	 * @return
	 */
	@AutoLog(value = "mdm_material-添加")
	@ApiOperation(value="mdm_material-添加", notes="mdm_material-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody MdmMaterialPage mdmMaterialPage) {
		MdmMaterial mdmMaterial = new MdmMaterial();
		BeanUtils.copyProperties(mdmMaterialPage, mdmMaterial);
		mdmMaterialService.saveMain(mdmMaterial, mdmMaterialPage.getMdmMaterialFactoryDetailList(),mdmMaterialPage.getMdmMaterialFinanceDetailList(),mdmMaterialPage.getMdmMaterialUnitDetailList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mdmMaterialPage
	 * @return
	 */
	@AutoLog(value = "mdm_material-编辑")
	@ApiOperation(value="mdm_material-编辑", notes="mdm_material-编辑")
	@PutMapping(value = "/editMain")
	public Result<?> editMain(@RequestBody MdmMaterialPage mdmMaterialPage) {
		MdmMaterial mdmMaterial = new MdmMaterial();
		BeanUtils.copyProperties(mdmMaterialPage, mdmMaterial);
		MdmMaterial mdmMaterialEntity = mdmMaterialService.getById(mdmMaterial.getId());
		if(mdmMaterialEntity==null) {
			return Result.error("未找到对应数据");
		}
		mdmMaterialService.updateMain(mdmMaterial, mdmMaterialPage.getMdmMaterialFactoryDetailList(),mdmMaterialPage.getMdmMaterialFinanceDetailList(),mdmMaterialPage.getMdmMaterialUnitDetailList());
		return Result.OK("编辑成功!");
	}

	/**
	 *  编辑
	 *
	 * @param mdmMaterial
	 * @return
	 */
	@AutoLog(value = "mdm_material-编辑")
	@ApiOperation(value="mdm_material-编辑", notes="mdm_material-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody MdmMaterial mdmMaterial) {
		mdmMaterialService.updateById(mdmMaterial);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "mdm_material-通过id删除")
	@ApiOperation(value="mdm_material-通过id删除", notes="mdm_material-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		mdmMaterialService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "mdm_material-批量删除")
	@ApiOperation(value="mdm_material-批量删除", notes="mdm_material-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.mdmMaterialService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "mdm_material-通过id查询")
	@ApiOperation(value="mdm_material-通过id查询", notes="mdm_material-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		MdmMaterial mdmMaterial = mdmMaterialService.getById(id);
		if(mdmMaterial==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mdmMaterial);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "工厂视图通过主表ID查询")
	@ApiOperation(value="工厂视图主表ID查询", notes="工厂视图-通主表ID查询")
	@GetMapping(value = "/queryMdmMaterialFactoryDetailByMainId")
	public Result<?> queryMdmMaterialFactoryDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<MdmMaterialFactoryDetail> mdmMaterialFactoryDetailList = mdmMaterialFactoryDetailService.selectByMainId(id);
		return Result.OK(mdmMaterialFactoryDetailList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "财务视图通过主表ID查询")
	@ApiOperation(value="财务视图主表ID查询", notes="财务视图-通主表ID查询")
	@GetMapping(value = "/queryMdmMaterialFinanceDetailByMainId")
	public Result<?> queryMdmMaterialFinanceDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<MdmMaterialFinanceDetail> mdmMaterialFinanceDetailList = mdmMaterialFinanceDetailService.selectByMainId(id);
		return Result.OK(mdmMaterialFinanceDetailList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "计量单位通过主表ID查询")
	@ApiOperation(value="计量单位主表ID查询", notes="计量单位-通主表ID查询")
	@GetMapping(value = "/queryMdmMaterialUnitDetailByMainId")
	public Result<?> queryMdmMaterialUnitDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<MdmMaterialUnitDetail> mdmMaterialUnitDetailList = mdmMaterialUnitDetailService.selectByMainId(id);
		return Result.OK(mdmMaterialUnitDetailList);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param mdmMaterial
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, MdmMaterial mdmMaterial) {
		// Step.1 组装查询条件查询数据
		QueryWrapper<MdmMaterial> queryWrapper = QueryGenerator.initQueryWrapper(mdmMaterial, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<MdmMaterial> queryList = mdmMaterialService.list(queryWrapper);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<MdmMaterial> mdmMaterialList = new ArrayList<MdmMaterial>();
		if(oConvertUtils.isEmpty(selections)) {
			mdmMaterialList = queryList;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			mdmMaterialList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}

		// Step.3 组装pageList
		List<MdmMaterialPage> pageList = new ArrayList<MdmMaterialPage>();
		for (MdmMaterial main : mdmMaterialList) {
			MdmMaterialPage vo = new MdmMaterialPage();
			BeanUtils.copyProperties(main, vo);
			List<MdmMaterialFactoryDetail> mdmMaterialFactoryDetailList = mdmMaterialFactoryDetailService.selectByMainId(main.getId());
			vo.setMdmMaterialFactoryDetailList(mdmMaterialFactoryDetailList);
			List<MdmMaterialFinanceDetail> mdmMaterialFinanceDetailList = mdmMaterialFinanceDetailService.selectByMainId(main.getId());
			vo.setMdmMaterialFinanceDetailList(mdmMaterialFinanceDetailList);
			List<MdmMaterialUnitDetail> mdmMaterialUnitDetailList = mdmMaterialUnitDetailService.selectByMainId(main.getId());
			vo.setMdmMaterialUnitDetailList(mdmMaterialUnitDetailList);
			pageList.add(vo);
		}

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "mdm_material列表");
		mv.addObject(NormalExcelConstants.CLASS, MdmMaterialPage.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("mdm_material数据", "导出人:"+sysUser.getRealname(), "mdm_material"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<MdmMaterialPage> list = ExcelImportUtil.importExcel(file.getInputStream(), MdmMaterialPage.class, params);
				for (MdmMaterialPage page : list) {
					MdmMaterial po = new MdmMaterial();
					BeanUtils.copyProperties(page, po);
					mdmMaterialService.saveMain(po, page.getMdmMaterialFactoryDetailList(),page.getMdmMaterialFinanceDetailList(),page.getMdmMaterialUnitDetailList());
				}
				return Result.OK("文件导入成功！数据行数:" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.OK("文件导入失败！");
	}

}
